//
//  BoardViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/15.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "BoardViewController.h"
#import "getCommonDataMode.h"
#import "GoodsModel.h"
#import "homeVCCell.h"
#import "SupplyPurchasingCell.h"
#import "SupplyOfGoodsModel.h"
#import "ProductDetailsViewController.h"
#import "PurchaseSubmitViewController.h"
@interface BoardViewController ()<MJRefreshBaseViewDelegate>{
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    NSMutableArray *provinceArray;
    int Page;
}
@property (nonatomic,strong) NSMutableArray *fakeData;
@end

@implementation BoardViewController
@synthesize selectView,viewData,type,menuData,bodyDic,fakeData,viewUrl,viewtype;
- (void)viewDidLoad {
    [super viewDidLoad];
    TABHIDDEN
    [self.leftBtn addTarget: self action: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];
    self.viewData = [NSMutableDictionary dictionary];
    self.bodyDic = [NSMutableDictionary dictionary];
    provinceArray = [NSMutableArray array];
    self.fakeData = [NSMutableArray array];
    NSString *filePath = FILE(@"getcommondata.txt");
    NSString *result = GETFILE(filePath);
    getCommonDataMode *model = [[getCommonDataMode alloc]init];
    [model parseResponseData:result];
    [self.viewData setObject:model.data forKey:@"data"];
    self.mainData = [NSMutableArray array];
    self.bodyDic = [NSMutableDictionary dictionary];
    if (self.type == 0) { //板材
        [self.bodyDic setObject:@"plank" forKey:@"type"];
//        [self.bodyDic setObject:@"100000000" forKey:@"material_id"];
    }else if (self.type == 1){ //门板
        [self.bodyDic setObject:@"doorplank" forKey:@"type"];
//        [self.bodyDic setObject:@"300000000" forKey:@"material_id"];
    }else{ //装饰纸
        [self.bodyDic setObject:@"paper" forKey:@"type"];
//        [self.bodyDic setObject:@"200000000" forKey:@"material_id"];
    }
    [self.bodyDic setObject:@"" forKey:@"material_id"];
    [self.bodyDic setObject:@"" forKey:@"province_id"];
    [self.bodyDic setObject:@"" forKey:@"brand_id"];
    [self superMainVC];
    // Do any additional setup after loading the view.
}
-(void)superMainVC{
    NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"品种",@"品牌",@"货源地", nil];
    self.menuData = arr;
    UIView *tempView = [self createViewFrame:CGRectMake(0, 64, SWIDTH, 44) bgColor:[UIColor whiteColor] tag:0];
    [self.view addSubview:tempView];
    for (int i = 0; i < [arr count]; i++) {
        UIButton *button = [self createNavButton:CGRectMake((SWIDTH /3)*i, 64, SWIDTH/3, 44) title:[arr objectAtIndex:i] Tag:10+i];
        button.backgroundColor = [UIColor clearColor];
        [button setTitleColor:GRAYColor forState:0];
        [self.view addSubview:button];
        if (i !=0) {
            UIView *line = [self createViewFrame:CGRectMake((SWIDTH/3)*i-1, 4, 1, 44 - 8) bgColor:[UIColor grayColor] tag:0];
            line.alpha = 0.2;
            [tempView addSubview:line];
        }
    }
    UIView *line = [self createViewFrame:CGRectMake(0, 43.5, SWIDTH, 0.5) bgColor:UIColorFromRGB(0xe8e8e8) tag:0];
    [tempView addSubview:line];
    self.mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 108, SWIDTH, VHEIGHT - 44) style:UITableViewStylePlain];
    [self.mainTableView setDataSource:self];
    [self.mainTableView setDelegate:self];
    [self.mainTableView setBackgroundColor:[UIColor clearColor]];
    UIView *theView = [[UIView alloc] initWithFrame:self.mainTableView.frame];
    [theView setBackgroundColor:[UIColor clearColor]];
    [self.mainTableView setBackgroundView:theView];
    [self.view addSubview:self.mainTableView];
    TABELVIEW(self.mainTableView);
    [self addHeader];
    [self addFooter];
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *path = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
        [self performSelectorOnMainThread:@selector(updateCity:) withObject:path waitUntilDone:YES];
    });
}
-(void)updateCity:(NSString *)path{
    NSData *jsonData = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:nil];
    NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    for (int i = 0; i < [arr count]; i++) {
        NSMutableDictionary *province = [arr objectAtIndex:i];
        if (![Unity isBlankString:[province objectForKey:@"level"]]) {
            if ([[province objectForKey:@"level"] isEqualToString:@"1"]) {
                [provinceArray addObject:province];
            }
        }
    }
}
-(void)returnDataFromRequest:(NSString*)url{
    TIME
    HEADDIC(nowTime, url);
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:HEAD forKey:@"head"];
    [dic setObject:self.bodyDic forKey:@"body"];
    requestManage *request =[[requestManage alloc]init];
    NSString *result = [request post:APPIP postDataDic:dic error:nil];
    GoodsModel *model = [[GoodsModel alloc]init];
    [model parseResponseData:result];
    UIImageView *imageView = (UIImageView *)[self.mainTableView viewWithTag:981];
    UILabel *lab = (UILabel *)[self.mainTableView viewWithTag:982];
    if (Page == 1) {
        if ([self.fakeData count]!=0) {
            [self.fakeData removeAllObjects];
        }
        if ([model.listData count]!=0) {
            for (int i = 0; i <[model.listData count]; i++) {
                [self.fakeData addObject:[model.listData objectAtIndex:i]];
            }
        }
    }else{
        [self.fakeData addObjectsFromArray:model.listData];
    }
    if ([self.fakeData count]!=0) {
        if (imageView) {
            [imageView setHidden:YES];
            [lab setHidden:YES];
        }
        [self.mainTableView setHidden:NO];
        [self.mainTableView reloadData];
    }else{
        [self.mainTableView reloadData];
        if (imageView) {
            [imageView setHidden:NO];
            [lab setHidden:NO];
        }else{
            [self drawNullView];
        }
    }
    
}
- (void)drawNullView{
    UIImageView *imageView = [self createImageViewFrame:CGRectMake((SWIDTH - 47)/2, (self.mainTableView.frame.size.height-44 - 63)/2, 47, 63) image:nil imageName:@"暂无采购标识" tag:981];
    [self.mainTableView addSubview:imageView];
    NSString *title = @"";
    if ([self.viewUrl isEqualToString:PURCHAESLIST]) {
        title = [NSString stringWithFormat:@"抱歉，没有找到您要的采购信息"];
    }else{
        title = [NSString stringWithFormat:@"抱歉，没有找到您要的货源"];
    }
    UILabel *textLab = [self createLabelFrame:CGRectMake(0, (self.mainTableView.frame.size.height-44 - 55)/2 + 65, SWIDTH, 14) title:title titleColor:UIColorFromRGB(0xdedede) tag:982];
    textLab.font = [UIFont systemFontOfSize:14];
    textLab.textAlignment = NSTextAlignmentCenter;
    [self.mainTableView addSubview:textLab];
}
-(void)removeBrandView{
    UIButton *button1 = (UIButton *)[self.view viewWithTag:10];
    UIButton *button2 = (UIButton *)[self.view viewWithTag:11];
    UIButton *button3 = (UIButton *)[self.view viewWithTag:12];
    UIView *bgView =(UIView *)[self.navigationController.view viewWithTag:890];
    varietiesView *varietiesV = (varietiesView *)[self.view viewWithTag:110];
    if (varietiesV) {
        button1.selected = NO;
        [varietiesV removeFromSuperview];
        varietiesV = nil;
    }
    brandView *brandV = (brandView *)[self.view viewWithTag:111];
    if (brandV) {
        button2.selected = NO;
        [brandV removeFromSuperview];
        brandV = nil;
    }
    supplyLandView *supplyV = (supplyLandView *)[self.view viewWithTag:112];
    if (supplyV) {
        button3.selected = NO;
        [supplyV removeFromSuperview];
        supplyV = nil;
    }
    if (bgView) {
        [bgView removeFromSuperview];
        bgView = nil;
    }
    
}
-(void)buttonClick:(UIButton *)sender{
    //TODO: 按钮点击选择事件
    UIButton *button1 = (UIButton *)[self.view viewWithTag:10];
    UIButton *button2 = (UIButton *)[self.view viewWithTag:11];
    UIButton *button3 = (UIButton *)[self.view viewWithTag:12];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeBrandView)];
    UIView *bgView =(UIView *)[self.navigationController.view viewWithTag:890];
    if (bgView) {
        [bgView removeFromSuperview];
        bgView = nil;
    }
    NSMutableDictionary *data = [self.viewData objectForKey:@"data"];
    varietiesView *varietiesV = (varietiesView *)[self.view viewWithTag:110];
    if (varietiesV) {
        [varietiesV removeFromSuperview];
        varietiesV = nil;
    }
    brandView *brandV = (brandView *)[self.view viewWithTag:111];
    if (brandV) {
        [brandV removeFromSuperview];
        brandV = nil;
    }
    supplyLandView *supplyV = (supplyLandView *)[self.view viewWithTag:112];
    if (supplyV) {
        [supplyV removeFromSuperview];
        supplyV = nil;
    }
    UIView *bgView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, 64)];
    bgView1.tag = 890;
    [bgView1 setBackgroundColor:[UIColor clearColor]];
    [bgView1 addGestureRecognizer:tap];
    bgView1.userInteractionEnabled = YES;
    [self.navigationController.view addSubview:bgView1];
    if (sender.tag == 10) {
        // 品种
        if (sender.selected == NO) {
            button2.selected = NO;
            button3.selected = NO;
            sender.selected = YES;
            varietiesV = [[varietiesView alloc]initWithFrame:CGRectMake(0, 108, SWIDTH, VHEIGHT - 44)];
            [varietiesV setBackgroundColor:[UIColor whiteColor]];
            varietiesV.tag = 110;
            varietiesV.delegate = self;
            UILabel *lab = (UILabel *)[sender viewWithTag:2];
            varietiesV.selectVarieties = lab.text;
            switch (type) {
                case showTypePlank:
                    [varietiesV reloadView:[[data objectForKey:@"materials"] objectForKey:@"plank"]];
                    break;
                case showTypePaper:
                    [varietiesV reloadView:[[data objectForKey:@"materials"] objectForKey:@"paper"]];
                    break;
                case showTypeDoorplank:
                    [varietiesV reloadView:[[data objectForKey:@"materials"] objectForKey:@"doorplank"]];
                    break;
                default:
                    break;
            }
            [self.view addSubview:varietiesV];
        }else{
            sender.selected = NO;
            varietiesView *varietiesV = (varietiesView *)[self.view viewWithTag:110];
            if (varietiesV) {
                [varietiesV removeFromSuperview];
                varietiesV = nil;
            }
        }
        
    }else if (sender.tag == 11){
        // 品牌
        if (sender.selected == NO) {
            button1.selected = NO;
            button3.selected = NO;
            sender.selected = YES;
            brandV = [[brandView alloc]initWithFrame:CGRectMake(0, 108, SWIDTH, VHEIGHT - 44)];
            brandV.mainData = [data objectForKey:@"brands"];
            brandV.tjData = [data objectForKey:@"tj_brands"];
            brandV.delegate = self;
            UILabel *lab = (UILabel *)[sender viewWithTag:2];
            brandV.selectString = lab.text;
            brandV.tag = 111;
            [brandV setBackgroundColor:[UIColor whiteColor]];
            [self.view addSubview:brandV];
            [brandV reloadView];
        }else{
            sender.selected = NO;
            brandView *brandV = (brandView *)[self.view viewWithTag:111];
            if (brandV) {
                [brandV removeFromSuperview];
                brandV = nil;
            }
        }
    }else if (sender.tag == 12){
        // 货源地
        if (sender.selected == NO) {
            button2.selected = NO;
            button1.selected = NO;
            sender.selected = YES;
            supplyV = [[supplyLandView alloc]initWithFrame:CGRectMake(0, 108, SWIDTH, VHEIGHT - 44)];
            supplyV.mainData = provinceArray;
            supplyV.tag = 112;
            supplyV.delegate = self;
            UILabel *lab = (UILabel *)[sender viewWithTag:2];
            [supplyV reloadView:lab.text];
            [self.view addSubview:supplyV];
            [supplyV setBackgroundColor:[UIColor whiteColor]];
        }else{
            sender.selected = NO;
            supplyLandView *supplyV = (supplyLandView *)[self.view viewWithTag:112];
            if (supplyV) {
                [supplyV removeFromSuperview];
                supplyV = nil;
            }
        }
    }
}
-(void)selectBrand:(tj_brandsModel*)dic{
    UIButton *button = (UIButton *)[self.view viewWithTag:11];
    UILabel *lab = (UILabel *)[button viewWithTag:2];
    UIImageView *imageView = (UIImageView *)[button viewWithTag:1200];
    if (![dic.name isEqualToString:@"全部"]) {
        lab.text = dic.name;
    }else{
        lab.text = @"品牌";
    }
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize titleSize = [lab.text sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, 44)];
    int width = button.frame.size.width/2 + titleSize.width/2+7;
    if (width + 18 > button.frame.size.width) {
        imageView.frame = CGRectMake(button.frame.size.width - 10, (button.frame.size.height - 5)/2, 7, 5);
    }else{
        imageView.frame = CGRectMake(width, (button.frame.size.height - 5)/2, 7, 5);
    }
    button.selected = NO;
    brandView *supplyV = (brandView *)[self.view viewWithTag:111];
    if (supplyV) {
        [supplyV removeFromSuperview];
        supplyV = nil;
    }
    [self.bodyDic setObject:dic.brand_id forKey:@"brand_id"];
    [_header beginRefreshing];
}
-(void)selectSupplyLand:(NSMutableDictionary *)dic{
    UIButton *button = (UIButton *)[self.view viewWithTag:[self.menuData count] + 9];
    UILabel *lab = (UILabel *)[button viewWithTag:2];
    UIImageView *imageView = (UIImageView *)[button viewWithTag:1200];
    if (![[dic objectForKey:@"city"] isEqualToString:@"全部"]) {
        lab.text = [dic objectForKey:@"city"];
    }else{
        lab.text = @"货源地";
    }
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize titleSize = [lab.text sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, 44)];
    int width = button.frame.size.width/2 + titleSize.width/2+7;
    if (width + 18 > button.frame.size.width) {
        imageView.frame = CGRectMake(button.frame.size.width - 10, (button.frame.size.height - 5)/2, 7, 5);
    }else{
        imageView.frame = CGRectMake(width, (button.frame.size.height - 5)/2, 7, 5);
    }
    button.selected = NO;
    supplyLandView *supplyV = (supplyLandView *)[self.view viewWithTag:112];
    if (supplyV) {
        [supplyV removeFromSuperview];
        supplyV = nil;
    }
    [self.bodyDic setObject:[dic objectForKey:@"id"] forKey:@"province_id"];
    [_header beginRefreshing];
}
-(void)dissMissVarietiesView:(id)obj{
    UIButton *button = (UIButton *)[self.view viewWithTag:10];
    plankModel *model = (plankModel *)obj;
    UILabel *lab = (UILabel *)[button viewWithTag:2];
    UIImageView *imageView = (UIImageView *)[button viewWithTag:1200];
    if (![model.name isEqualToString:@"全部"]) {
        lab.text = model.name;
    }else{
        lab.text = @"品种";
    }
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize titleSize = [lab.text sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, 44)];
    int width = button.frame.size.width/2 + titleSize.width/2+7;
    if (width + 18 > button.frame.size.width) {
        imageView.frame = CGRectMake(button.frame.size.width - 10, (button.frame.size.height - 5)/2, 7, 5);
    }else{
        imageView.frame = CGRectMake(width, (button.frame.size.height - 5)/2, 7, 5);
    }
    button.selected = NO;
    varietiesView *varietiesV = (varietiesView *)[self.view viewWithTag:110];
    if (varietiesV) {
        [varietiesV removeFromSuperview];
        varietiesV = nil;
    }
    [self.bodyDic setObject:model.material_id forKey:@"material_id"];
    [_header beginRefreshing];

}
- (void)addFooter
{    __unsafe_unretained BoardViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.mainTableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page++;
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是footer
        [self.bodyDic setObject:[NSNumber numberWithInt:Page] forKey:@"page"];
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    _footer = footer;
}

- (void)addHeader
{
    __unsafe_unretained BoardViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.mainTableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page = 1;
        //        [self dataSource:StateURL];
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是header
        [self.bodyDic setObject:[NSNumber numberWithInt:Page] forKey:@"page"];
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                break;
            case MJRefreshStatePulling:
                break;
            case MJRefreshStateRefreshing:
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self returnDataFromRequest:self.viewUrl];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.fakeData count];
}
// 返回哪一组的哪一行显示什么内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString* cellId = [NSString stringWithFormat:@"cellid%ld",(long)indexPath.row];
    
    if (viewtype == 0) {
        homeVCCell* cell = (homeVCCell*)[tableView dequeueReusableCellWithIdentifier:cellId];
        
        if(cell == nil){
            cell = [[homeVCCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId] ;
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        homeModelSupply *model = [self.fakeData objectAtIndex:indexPath.row];
        [cell goodsCellView:model];
        return cell;
    }else{
        SupplyPurchasingCell* cell = (SupplyPurchasingCell*)[tableView dequeueReusableCellWithIdentifier:cellId];
        
        if(cell == nil){
            cell = [[SupplyPurchasingCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId] ;
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        homeModelSupply *supply = [self.fakeData objectAtIndex:indexPath.row];
        [cell drawCell:supply];
        cell.button.tag = indexPath.row +300;
        [cell.button addTarget:self action:@selector(wantButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}
// 当每一行的cell的高度不一致的时候就使用代理方法设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 104;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (viewtype == 0) {
        ProductDetailsViewController *productDetailsVC = [[ProductDetailsViewController alloc]init];
        homeModelSupply *model = [self.fakeData objectAtIndex:indexPath.row];
        productDetailsVC.supply = model;
        [self.navigationController pushViewController:productDetailsVC animated:YES];
    }
}
-(void)wantButtonClick:(UIButton *)sender{
    PurchaseSubmitViewController *submitVC = [[PurchaseSubmitViewController alloc]init];
    homeModelSupply *model = [self.fakeData objectAtIndex:sender.tag - 300];
    submitVC.supply = model;
    submitVC.title = @"我要供货";
    [self.navigationController pushViewController:submitVC animated:YES];
}
-(UIButton *)createNavButton:(CGRect)frame
                       title:(NSString *)title
                         Tag:(NSInteger)tag{
    UIButton *button = [self createButtonFrame:frame title:nil viewController:self selector:@selector(buttonClick:) tag:tag];
    UIImageView *imageView = [self createImageViewFrame:CGRectMake(frame.size.width - 12, (frame.size.height - 5)/2, 7, 5) image:nil imageName:@"品种" tag:1200];
    [button addSubview:imageView];
    UILabel *lab = [self createLabelFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) title:title titleColor:GRAYColor tag:2];
    lab.font = [UIFont systemFontOfSize:14];
    lab.textAlignment = NSTextAlignmentCenter;
    [button addSubview:lab];
    UIFont *font = [UIFont systemFontOfSize:14];
    CGSize titleSize = [lab.text sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, 44)];
    int width = button.frame.size.width/2 + titleSize.width/2 +7;
    imageView.frame = CGRectMake(width, (frame.size.height - 5)/2, 7, 5);
    return button;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
